package com.hddznet.uniplatform.sm.config.cas;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class CasSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

	@Autowired
    private CasUserDetailsService casUserDetailsService;
    @Autowired
    private CasAuthenticationSuccessHandler casAuthenticationSuccessHandler;
    @Autowired
    private CasAuthenticationFailureHandler casAuthenticationFailureHandler;


    public CasSecurityConfig() {
        log.info("casSecurityConfig loading ...");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
    	CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter("/cas/client/auth");

    	casAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
    	casAuthenticationFilter.setAuthenticationSuccessHandler(casAuthenticationSuccessHandler);
    	casAuthenticationFilter.setAuthenticationFailureHandler(casAuthenticationFailureHandler);

    	CasUserDetailsAuthenticationProvider casUserDetailsAuthenticationProvider = new CasUserDetailsAuthenticationProvider(casUserDetailsService);

        http.authenticationProvider(casUserDetailsAuthenticationProvider)
                .addFilterAfter(casAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
